<template>
  <div
    class="myButtonWrapper"
    :style="{ backgroundColor: btnStatus ? activeColor : inactiveColor }"
    @click="changeBtnStatus($event)"
  >
    <span class="cirle" :class="[btnStatus ? 'rightStyle' : 'leftStyle']">
    </span>
  </div>
</template>
<script>
export default {
  name: 'mySwitchButton',
  /* 自定义组件的 v-model: https://cn.vuejs.org/v2/guide/components-custom-events.html#%E8%87%AA%E5%AE%9A%E4%B9%89%E7%BB%84%E4%BB%B6%E7%9A%84-v-model */
  props: {
    value: {
      type: Boolean,
      default: false // 左边是false
    },
    'active-color': {
      type: String,
      default: '#e7e5e5',
      validator: function (value) {
        const result = value ?? ''
        if (!result) {
          console.warn('Invalid active-color payload!')
        }
        return Boolean(result)
      }
    },
    'inactive-color': {
      type: String,
      default: '#e7e5e5'
    }
  },
  // vue2只能有一个v-model在自定义组件中
  model: {
    prop: 'value',
    event: 'updateValue' // 自定义事件名字
  },
  data() {
    return {}
  },
  methods: {
    changeBtnStatus(e) {
      // console.log(e)
      this.btnStatus = !this.btnStatus
    }
  },
  computed: {
    btnStatus: {
      get: function () {
        return this.value
      },
      set: function (val) {
        this.$emit('updateValue', val) // 这里的事件名字一定是 'update:' + prop的名字(除非我们自己定义了事件名字)
        this.$emit('BtnClickafter', val)
      }
    }
  },
  activated: {},
  deactivated: {}
}
</script>
<style lang="less" scoped>
.myButtonWrapper {
  position: relative;
  display: flex;
  align-items: center;
  box-sizing: border-box;
  width: 40px;
  height: 25px;
  border-radius: calc(40px / 2);
  border: 1px solid #a0c5e8;
  cursor: pointer;
  transition: background-color 0.2s ease;

  /*      */
  .cirle {
    position: absolute;
    display: inline-block;
    width: calc(100% / 1.8);
    padding-top: calc(100% / 1.8);
    border-radius: 100%;
    transition: background-color 0.2s ease, left 0.2s ease;
  }

  .leftStyle {
    background-color: #333333;
    left: 0px;
  }
  .rightStyle {
    left: calc(100% - (100% / 1.8));
    background-color: #f1f1f1;
  }
}
</style>
